package com.morrislabs.facebook
{
    import com.facebook.Facebook;
    import com.facebook.events.FacebookEvent;
    import com.facebook.facebook_internal;
    import com.facebook.session.WebSession;
    
    import flash.display.LoaderInfo;
    import flash.external.ExternalInterface;
    
    import mx.controls.Alert;
	
		
	public class FacebookLogin
	{
		private var fbook:Facebook;
		private var fbSession: WebSession;
		private var fbLoaderInfo:LoaderInfo;
		
        private var errorMessage:String;	
        private var _callbackAfterConnect: Function;	


		public function FacebookLogin()
		{	
		}
		

		public function get callbackAfterConnect():Function 
		{ 
			return this._callbackAfterConnect; 
		}
		public function set callbackAfterConnect(f:Function):void 
		{ 
			this._callbackAfterConnect = f; 
		}
		
		
		
		public function connect(fbl:LoaderInfo, callback:Function=null):void
		{
			fbLoaderInfo = fbl;
			
			if (callback != null) 
				this.callbackAfterConnect = callback;
			
			fbLogin(); 			
		}
		
		public function getHandle():Facebook
		{
			return fbook;
		}
		
		public function isConnected():Boolean
		{
			return (fbSession && fbook.is_connected);
		}
		
		public function getLastError():String
		{
			return errorMessage;
		}		

		private function fbLogin( ):void
		{		
			if (!ExternalInterface.available) {
                errorMessage = "Must be run from inside a webpage";
                Alert.show(errorMessage);
                return;
            }
 			
            // swf was loaded from a facebook iframe canvas so session info should
            // have been included in flashvars from the javascript. 
            if (fbLoaderInfo.parameters.fb_sig_in_iframe) 
            {
                trace("[fbLogin] Connecting from a facebook iframe canvas");
                fbConnect(fbLoaderInfo.parameters);
            }
            
            // swf was loaded from a facebook connect site,
            // request session info from javascript.
            else 
            {
                trace("[fbLogin] Connecting from a facebook connect site.");
                ExternalInterface.addCallback("updateConnection", fbConnect);
                ExternalInterface.call("initFacebook");
            }           			
		}
				
	    // Attempt to start a web session with the fb_sig_ values in the given parameters object
        private function fbConnect(parameters:Object) : void 
        {
            if (parameters.fb_sig_api_key && parameters.fb_sig_ss && parameters.fb_sig_session_key) 
            {	
                fbSession = new WebSession(parameters.fb_sig_api_key, parameters.fb_sig_ss, parameters.fb_sig_session_key);
                fbSession.facebook_internal::_uid = parameters.fb_sig_user;
        
                //Create our facebook instance
                fbook = new Facebook();
                fbSession.addEventListener(FacebookEvent.CONNECT, fbOnConnectHandler);
                fbook.startSession(fbSession);
                trace("[fbConnect] Verifying session.");
                fbSession.verifySession();
            } else {
                // couldn't authenticate an open connection
                // so ask the user to log into Facebook
                //errorMessage = "Not Connected.";
                trace("[fbConnect] asking user to log into Facebook.");
                promptConnect();
            }
        }		

		private function fbOnConnectHandler( event:FacebookEvent ):void
		{
			fbSession.removeEventListener(FacebookEvent.CONNECT, fbOnConnectHandler);
			trace("[fbOnConnectHandler] event: " + event.toString());
			
            if (event.error) 
            {
                errorMessage = "(" + event.error.errorCode + ") " + event.error.errorMsg;
                Alert.show(errorMessage);
            } else if (event.success) {			
				//Do the callback to start getting data
				//NthDegrees.getInstance().fbImport.getFriendsData();
				if (this.callbackAfterConnect != null)
					this.callbackAfterConnect.call(this);
            }
		}
		
        private function promptConnect() : void {
            if (ExternalInterface.available) {
                ExternalInterface.call("promptConnect");
            }
        }
            		
	}
}